package com.huidu.bitrade.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.huidu.bitrade.constant.TransactionType;
import com.huidu.bitrade.dto.MemberParentUserDTO;
import com.huidu.bitrade.entity.*;
import com.huidu.bitrade.mapper.AcMemberMapper;
import com.huidu.bitrade.service.*;
import com.huidu.bitrade.service.impl.DefaultPurchaseService;
import com.huidu.bitrade.util.MessageResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.skywalking.apm.toolkit.trace.ActiveSpan;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Api(tags = "推荐人修改")
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("rollBack")
public class AwardRollBackController
{
    private final NewMemberService newMemberService;
    private final AcMemberMapper acMemberMapper;
    private final AcReferrerRewardsService acReferrerRewardsService;
    private final DefaultPurchaseService defaultPurchaseService;
    private final MemberService memberService;
    @ApiOperation(value = "修改推荐人，并且重新发放奖励")
    @PostMapping("inviteAward")
    @Transactional(rollbackFor = Exception.class)
    public MessageResult<List<DeductMemberVo>> inviteAward(@RequestBody InviteAwardParam inviteAwardParam){
        //查询用户和推荐人
        Member member = memberService.findByPhone(inviteAwardParam.getPhone());
        Member inviteMember = memberService.findByPhone(inviteAwardParam.getInviterPhone());
        List<DeductMemberVo> list = new ArrayList<>();
        //用户有星级，回退之前奖励，重新发放奖励
        if(Objects.nonNull(member.getMemberStar())&&member.getMemberStar()>0){
            //如果之前推荐人不为空，修改奖励记录
            if(Objects.nonNull(member.getInviterId())){
                //查询用户购买节点记录
                List<AcMember> acMembers = acMemberMapper.selectList(Wrappers.<AcMember>lambdaQuery().select(AcMember::getMemberStar)
                        .eq(AcMember::getMemberId,member.getId())
                        .groupBy(AcMember::getBatchCode,AcMember::getMemberStar));
                if(CollectionUtils.isEmpty(acMembers)){
                    return MessageResult.error("用户有星级无购买节点记录，请核对信息");
                }
                for (AcMember acMember:acMembers){
                    //查询当前星级的奖励记录
                    List<AcReferrerRewards> referrerRewards = acReferrerRewardsService.list(Wrappers.<AcReferrerRewards>lambdaQuery()
                            .eq(AcReferrerRewards::getMemberId,member.getId())
                            .ne(AcReferrerRewards::getStatus,2)
                            .eq(AcReferrerRewards::getMemberStar,acMember.getMemberStar()));
                    if(CollectionUtils.isEmpty(referrerRewards)){
                        log.info("========用户购买星级"+acMember.getMemberStar()+"无奖励记录，请核对信息==========");
                        continue;
                    }
                    //减掉之前发放的奖励
                    for (AcReferrerRewards acReferrerRewards:referrerRewards){
//                        OtcCoin otcCoin = new OtcCoin();
//                        otcCoin.setUnit("CNHD");
//                        MemberWallet memberWallet = memberWalletService.findByOtcCoinAndMemberId(otcCoin, acReferrerRewards.getToMemberId());
//                        if(Objects.isNull(memberWallet)){
//                            throw new RuntimeException("未找到用户CNHD钱包");
//                        }
                        list.add(DeductMemberVo.builder().memberId(acReferrerRewards.getToMemberId())
                                .memberStar(acReferrerRewards.getMemberStar())
                                .createTime(acReferrerRewards.getCreateTime().toString())
                                .price(acReferrerRewards.getNumber()).build());
                        //状态修改为取消：status=2
                        acReferrerRewards.setStatus(2);
                        //减掉余额
//                    memberWalletService.operateDeductBalance(memberWallet, BigDecimal.valueOf(0).subtract(acReferrerRewards.getNumber()), TransactionType.ROUTING_BUY);
//                    acReferrerRewardsService.removeById(acReferrerRewards.getId());
                    }
                    acReferrerRewardsService.updateBatchById(referrerRewards);
                }
            }
            //减完余额之后，修改推荐人重新发放奖励
            memberService.updateInviterId(member.getId(),inviteMember.getId());
            //查询新的推荐人关系，发放奖励
            MemberParentUserDTO memberParentUserDTO = newMemberService.findUserAndParentById(member.getId());
            if (CollectionUtils.isEmpty(memberParentUserDTO.getParentId())) {
                log.info("未查询到推荐人，memberId:{}", member.getId());
                return MessageResult.error("未查询到星级推荐人，推荐关系已修改");
            }
            //重新发放奖励，按照用户当前星级发放一次
            defaultPurchaseService.rollRecord(memberParentUserDTO,memberParentUserDTO.getParentId());
        }else{
           //修改推荐人关系
            memberService.updateInviterId(member.getId(),inviteMember.getId());
        }
        return MessageResult.success("成功",list);
    }

    @Data
    public static class InviteAwardParam{
        @ApiModelProperty("用户手机号")
        private String phone;

        @ApiModelProperty("推荐人手机号")
        private String inviterPhone;
    }


    @Data
    @Builder
    public static class DeductMemberVo{
        @ApiModelProperty("需要扣除金额")
        private BigDecimal price;

        @ApiModelProperty("用户id")
        private Long memberId;

        @ApiModelProperty("扣除币种")
        private String coin = "CNHD";

        @ApiModelProperty("用户星级")
        private Integer memberStar;

        @ApiModelProperty("创建时间")
        private String createTime;
    }

}
